// docs.js
// Load all tasks from chrome.storage.local, extract all document links from notes, and render them as cards

document.addEventListener('DOMContentLoaded', function() {
  loadAndRenderDocs();
});

function loadAndRenderDocs() {
  if (!(window.chrome && chrome.storage && chrome.storage.local)) {
    showNotification('chrome.storage.local is not available!', 'error');
    return;
  }
  chrome.storage.local.get(['taskTrackerTasks'], function(result) {
    const tasks = result.taskTrackerTasks || [];
    const docLinks = extractAllDocLinks(tasks);
    renderDocsList(docLinks);
  });
}

// Extract all document links from all tasks' notes
function extractAllDocLinks(tasks) {
  const links = [];
  tasks.forEach(task => {
    if (!task.notes) return;
    // Match markdown links: [title](url)
    const mdLinks = Array.from(task.notes.matchAll(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g));
    mdLinks.forEach(match => {
      links.push({
        title: match[1],
        url: match[2],
        taskTitle: task.title,
        taskId: task.id
      });
    });
    // Match bare URLs (not already in markdown)
    const urlRegex = /(?<!\]\()\bhttps?:\/\/[^\s)]+/g;
    const bareLinks = Array.from(task.notes.matchAll(urlRegex));
    bareLinks.forEach(match => {
      // Avoid duplicates
      if (!links.some(l => l.url === match[0])) {
        links.push({
          title: match[0],
          url: match[0],
          taskTitle: task.title,
          taskId: task.id
        });
      }
    });
  });
  return links;
}

function renderDocsList(links) {
  const list = document.getElementById('docs-list');
  list.innerHTML = '';
  if (!links.length) {
    list.innerHTML = '<li style="color:#aaa;font-size:15px;padding:24px 0;">No document links found in your tasks.</li>';
    return;
  }
  links.forEach(link => {
    const li = document.createElement('li');
    li.className = 'doc-card';
    li.innerHTML = `
      <div class="doc-title">${escapeHtml(link.title)}</div>
      <a class="doc-link" href="${link.url}" target="_blank" rel="noopener noreferrer">${link.url}</a>
      <div class="doc-meta">From task: <b>${escapeHtml(link.taskTitle)}</b></div>
    `;
    list.appendChild(li);
  });
}

function escapeHtml(str) {
  return str.replace(/[&<>"']/g, function(tag) {
    const chars = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#39;'
    };
    return chars[tag] || tag;
  });
}

function showNotification(message, type = 'success') {
  const notification = document.getElementById('notification');
  const messageElement = document.getElementById('notification-message');
  notification.className = 'notification ' + type + ' show';
  messageElement.textContent = message;
  setTimeout(() => {
    notification.classList.remove('show');
  }, 3000);
} 